package cn.edu.bupt.springmvc.demo.controller;

import cn.edu.bupt.springmvc.demo.model.Person;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

@RestController
@RequestMapping("/rest")
public class RestDemoController {

    @GetMapping("/hello/{name}")
    public String sayHello(@PathVariable String name) {
        return "Hello " + name;
    }

    @GetMapping("/json-demo")
    public Person jsonDemo() {
        Person person = new Person();
        person.setName("小强");
        person.setAge(20);
        return person;
    }

    @GetMapping("/http-header")
    public String httpHeader(@RequestHeader("Referer") String referer,
                             HttpServletResponse response) {
        response.addHeader("new-header","test-value");
        return "referer: " + referer;
    }

    @GetMapping("/set-cookie")
    public String setCookie(HttpServletResponse response) {
        Cookie cookie = new Cookie("new-cookie", "bupt-1234");
        cookie.setPath("/");
        response.addCookie(cookie);
        return "cookie is set";
    }

    @GetMapping("/get-cookie")
    public String getCookie(@CookieValue(value = "new-cookie",required = false) String cookie_value) {
        return "new-cookie: " + cookie_value;
    }

    @GetMapping("/set-session")
    public String setSession(HttpSession session) {
        session.setAttribute("user-name","tom");
        return "set user-name in session";
    }

    @GetMapping("/get-session")
    public String getSession(@SessionAttribute(name = "user-name",required = false)  String user_name) {
        return "user-name: " + user_name;
    }

    @GetMapping("/mv-demo")
    public ModelAndView mvDemo() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("mv-demo");
        Person person = new Person();
        person.setName("小强");
        person.setAge(20);
        mv.addObject("person", person);
        return mv;
    }

    // http://127.0.0.1:8080/rest/exception-demo/not-integer-str/
    @GetMapping("/exception-demo/{num}")
    public String sayHello(@PathVariable Integer num) {
        return "num is: " + num;
    }

}
